package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Classes;
import com.ruoyi.system.domain.Course;
import com.ruoyi.system.domain.CoursePlan;
import com.ruoyi.system.domain.Grades;
import com.ruoyi.system.mapper.ClassesMapper;
import com.ruoyi.system.mapper.CourseMapper;
import com.ruoyi.system.mapper.GradesMapper;
import com.ruoyi.system.service.ICourseService;
import com.ruoyi.system.utils.Upload;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 课程表Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-22
 */
@Service
@Slf4j
public class CourseServiceImpl implements ICourseService {

    @Resource
    private GradesMapper gradesMapper;

    @Resource
    private ClassesMapper classesMapper;

    @Resource
    private CourseMapper courseMapper;


    /**
     * 上传课程表并解析
     *
     * @param file    文件
     * @param isCover 是否覆盖 1:覆盖 0:取消
     * @return
     * @throws IOException
     */
    @Override
    public int uploadAndSaveCourse(MultipartFile file, int isCover) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        log.info("拿到文件后缀 = " + suffix);
        if (!suffix.equals(".xlsx")) {
            log.error("上传文件失败,请检查格式,文件需为.xlsx类型");
            return 4;
        }
        XSSFWorkbook wb1 = new XSSFWorkbook(file.getInputStream());

        CoursePlan coursePlan = new CoursePlan();
        String[][] result;
        try {
            // 获取Excel表文件里的数据
            //第二个参数为从Excel文件里第几行开始读
            result = Upload.getFullData(wb1, 0);

            for (int i = 0; i < result.length; i++) {
                for (int j = 0; j < result[i].length - 1; j++) {
                    log.info("result[i][j] = " + "result[" + i + "][" + j + "] = " + result[i][j]);
                }
                if (i == 0) {
                    String yq = result[i][0];
                    String pattern = "([1-9]\\d*)|([零|一|二|三|四|五|六|七|八|九|十]+)";

                    Pattern r = Pattern.compile(pattern);
                    Matcher m = r.matcher(yq);
                    int f = 0;
                    while (m.find()) {
                        switch (f) {
                            case 0:
                                coursePlan.setYear(m.group().trim());
                                break;
                            case 1:
                                coursePlan.setQuarter(m.group().trim());
                                break;
                            case 2:
                                coursePlan.setGrade(m.group().trim() + "年级");
                                break;
                            case 3:
                                coursePlan.setClazz(m.group().trim() + "班");
                                break;
                            default:
                                break;
                        }
                        f++;
                    }
                }
                if (i > 1) {
                    coursePlan.getPeriod().add(result[i][0]);
                    coursePlan.getId().add(result[i][1]);
                    coursePlan.getMonday().add(result[i][2]);
                    coursePlan.getTuesday().add(result[i][3]);
                    coursePlan.getWednesday().add(result[i][4]);
                    coursePlan.getThursday().add(result[i][5]);
                    coursePlan.getFriday().add(result[i][6]);
                    coursePlan.getSaturday().add(result[i][7]);
                    coursePlan.getSunday().add(result[i][8]);
                }
            }

            //年度、学习、年级、班级 都不能为空
            if (StringUtils.isEmpty(coursePlan.getYear()) || StringUtils.isEmpty(coursePlan.getQuarter()) || StringUtils.isEmpty(coursePlan.getGrade()) || StringUtils.isEmpty(coursePlan.getClazz())) {
                return 5;
            }


            //年级不存在 或者 上传文件错误 （年级表中未找到上传文件中值）
            Grades grades = gradeNameIsExist(coursePlan.getGrade());
            if (null == grades) return 2;
            //班级不存在 或者 上传文件错误
            Classes classes = ClassNameIsExist(coursePlan.getClazz());
            if (null == classes) return 2;

            Course course = new Course();
            course.setCreateTime(DateUtils.getNowDate());
            course.setCreateBy(SecurityUtils.getLoginUser().getUsername());
            course.setGid(grades.getGid());
            course.setCid(classes.getCid());
            course.setYear_time(coursePlan.getYear());
            course.setSemester(coursePlan.getQuarter());
            course.setClass_num(JSONObject.toJSONString(coursePlan.getId()));
            course.setTime_period(JSONObject.toJSONString(coursePlan.getPeriod()));
            course.setMonday(JSONObject.toJSONString(coursePlan.getMonday()));
            course.setTuesday(JSONObject.toJSONString(coursePlan.getTuesday()));
            course.setWednesday(JSONObject.toJSONString(coursePlan.getWednesday()));
            course.setThursday(JSONObject.toJSONString(coursePlan.getThursday()));
            course.setFriday(JSONObject.toJSONString(coursePlan.getFriday()));
            course.setSaturday(JSONObject.toJSONString(coursePlan.getSaturday()));
            course.setSunday(JSONObject.toJSONString(coursePlan.getSunday()));

            //上传的课程内容，已经存在
            List<Course> coursesList = courseMapper.selectCourseList(course);
            if (1 == isCover) { //覆盖
                if (StringUtils.isNotEmpty(coursesList)) {
                    int i = courseMapper.deleteCourseByCoid(coursesList.get(0).getCoid());
                    log.info("删除课程表成功， 共删除： " + i);
                }
            } else { //不覆`盖
                if (StringUtils.isNotEmpty(coursesList) && coursesList.size() > 0)
                    return 3;
            }

            int i = courseMapper.insertCourse(course);
            log.info("批量添加第" + (i + 1) + "条课表信息完成");
            wb1.close();
            return 0;
        } catch (IOException e) {
            log.error("导入失败", e);
            e.printStackTrace();
        } finally {
            wb1.close();
        }
        return 1;
    }


    /**
     * 课程表下载
     *
     * @param response
     * @throws IOException
     */
    @Override
    public void export(HttpServletResponse response) throws IOException {

    }

    /**
     * 根据id删除课程表
     *
     * @param coids 课程表的主id
     * @return
     */
    @Override
    public int deleteCourseByCoids(Long[] coids) {
        return courseMapper.deleteCourseByCoids(coids);
    }

    /**
     * 修改课程表内容
     *
     * @param course
     * @return
     */
    @Override
    public int updateCourse(Course course) {
        course.setUpdateTime(DateUtils.getNowDate());
        course.setUpdateBy(SecurityUtils.getLoginUser().getUsername());
        return courseMapper.updateCourse(course);
    }

    /**
     * 课程表列表
     *
     * @param course
     * @return
     */
    @Override
    public List<Course> selectCourseList(Course course) {
        List<Grades> gradesList = gradesMapper.selectGradesList(new Grades());
        Map<Long, String> gradeNameMap = new HashMap<>();
        for (Grades grades : gradesList) {
            gradeNameMap.put(grades.getGid(), grades.getGradeName());
        }
        List<Classes> classesList = classesMapper.selectClassesList(new Classes());
        Map<Long, String> classesNameMap = new HashMap<>();
        for (Classes c : classesList) {
            classesNameMap.put(c.getCid(), c.getClassName());
        }
        List<Course> coursesList = courseMapper.selectCourseList(course);
        for (Course c : coursesList) {
            c.setGradeName(gradeNameMap.get(c.getGid()));
            c.setClassName(classesNameMap.get(c.getCid()));
        }
        return coursesList;
    }
    /**
     * 查询课程解析
     *
     * @param coid 课程解析主键
     * @return 课程解析
     */
    @Override
    public Course selectCourseByCoid(Long coid)
    {
        return courseMapper.selectCourseByCoid(coid);
    }



    /**
     * 判断年级否存在
     */
    private Grades gradeNameIsExist(String gradeName) {
        Grades grades = new Grades();
        grades.setGradeName(gradeName);
        List<Grades> gradesList = gradesMapper.selectGradesList(grades);
        if (gradesList.size() > 0) {
            return gradesList.get(0);
        }
        return null;
    }

    /**
     * 判断班级否存在
     */
    private Classes ClassNameIsExist(String className) {
        Classes classes = new Classes();
        classes.setClassName(className);
        List<Classes> classesList = classesMapper.selectClassesList(classes);
        if (classesList.size() > 0) {
            return classesList.get(0);
        }
        return null;
    }

}
